<template>
	<div class="companyManagement" curPageName="depman123456789">
		<layoutContent :toogleShow="false">
			<template #left>
				<treeNode :defTreeValue="org_ids" :treeLevel="1" @node-change="nodeChange"></treeNode>

			</template>
			<template #search>
				<!-- 搜索模块儿 -->
					<serachBar custom_class="myclass"
						:placeholder="$t('organization_departmentManagement.department_name')" :close-advanced=true
						:search_val=state.key_words @searchEvent="searchFn">
						<template #footer>
							<el-button type="primary" v-auth="{'authArr':authArr,'key':'depAdd'}"
								@click="onPlus">{{$t("organization_departmentManagement.add_dep")}}</el-button>
						</template>
					</serachBar>
			
			</template>
			<template #content>
					<MerakXTable ref="tableRef" v-bind="tablePayload" :query-columns="handleQueryColumns"
						:query-data="handleQueryData">

						<template #handler="{ row }">
							<div style="display: flex;">
								<el-button v-auth="{'authArr':authArr,'key':'depEdit'}" type="primary" link
									@click="saveEdit(row)">
									{{$t("merak.edit")}} </el-button>
								<el-button v-auth="{'authArr':authArr,'key':'depDel'}"
									:type="row.person_count?'':'danger'" link :disabled="row.person_count>0"
									@click="delCompany(row)">
									{{$t("merak.delete")}} </el-button>
							</div>
						</template>

					</MerakXTable>
				
			</template>
		</layoutContent>



		<!-- 弹窗模块儿 -->
		<div class="drawer">

			<el-dialog modal-class="merak_modal" v-model="drawerCompany" direction="rtl" :close-on-click-modal="false"
				:close-on-press-escape="false" width="700">
				<template #header>
					<div class="merak_modal_title">{{companyTitle}}</div>
				</template>
				<div class="companyPad">
					<el-form :model="companyForm" ref="companyRef" :rules="companyRules" label-position="top">
						<el-row :gutter="40">
							<el-col :span="12">
								<el-form-item :label="$t('organization_departmentManagement.org_cn')" prop="org_cn">
									<el-input class="qf_input" v-model="companyForm.org_cn" />
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item :label="$t('organization_departmentManagement.org_ru')" prop="org_ru">
									<el-input class="qf_input" v-model="companyForm.org_ru" />
								</el-form-item>
							</el-col>

							<el-col :span="12">
								<el-form-item :label="$t('organization_departmentManagement.dep_company')"
									prop="parent_id">
									<el-select class="qf_select" style="width: 100%;" v-model="companyForm.parent_id">
										<el-option v-for="cItem in companyList" :key="cItem.key" :label="cItem.value"
											:value="cItem.key" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item :label="$t('organization_companyManagement.personnel_size')">
									<el-input class="qf_input" v-number maxlength="3"
										v-model="companyForm.personnel_size" />

								</el-form-item>
							</el-col>
						</el-row>



					</el-form>

				</div>

				<template #footer>
					<el-button type="default" @click="cancelEmpty(companyRef)">{{$t("merak.cancel")}}</el-button>
					<el-button type="primary" plain v-if="editShow" :loading="loadingState"
						@click="saveContinue('2',companyRef)">{{$t("merak.save_continue")}}</el-button>
					<el-button type="primary" @click="submitForm('1',companyRef)"
						:loading="loadingState">{{$t("merak.save")}}</el-button>

				</template>
			</el-dialog>



		</div>


	</div>

</template>

<script setup lang="ts" name="departmentManagement">

	import { Plus, Edit, Delete, EditPen } from '@element-plus/icons-vue';
	import { ref, reactive, computed, getCurrentInstance, nextTick, onMounted } from "vue";
	import layoutContent from "@/components/LayoutComponents/index.vue";
	import { getAlltree } from "@/minxins/useOrgsStore";//获取组织架构树
	import serachBar from "@/components/SearchBar/index";
	import treeNode from '@/views/personalManagement/a-components/oragnizationTree/index.vue';
	import MerakXTable, { MerakXTableInstance, MerakXTableColumn, MerakXTableQuery } from "@/components/MerakXTable";
	import { Path, getTableColumns, getTableData } from "@/api/modules/table";
	import useLoading from "@/hooks/useLoading";
	import { getLocationParams } from "@/utils/index";
	// 使用队列 loading 管理初始化页面加载状态
	const { queueLoading, queueId } = useLoading();

	import { moreConfirm, confirmWarningMsg, successMsg, warnMsg, failMsg, confirmSuccessMsg, delConfimMsg } from "@/utils/messageUtils";
	import { getDepHeadApi, getOrgsListApi, getOrgsTableListApi, saveOrgsApi, delOrgsApi } from "@/api/modules/personalManagementApi/organization";

	const tableRef = ref < MerakXTableInstance > ();


	//#region 树节点点击
	const org_ids = ref(0);
	//接收url参数
	const newUrl = new URL(window.location.href);
	let url_org_id = getLocationParams(newUrl.href, 'org_id');
	org_ids.value = url_org_id ?? 0;


	const nodeChange = (data: any) => {
		console.log(data, "树节点值，，，，")
		let { org_id } = data;
		// 构建新的URL
		const newUrl = new URL(window.location.href);
		newUrl.searchParams.set('org_id', org_id);
		org_ids.value = org_id;
		// 使用pushState更新浏览器历史记录
		window.history.pushState({}, '', newUrl.toString());
		state.org_id = org_id == 0 ? '' : org_id;

	}

	//#endregion


	//#region 表单编辑

	const companyRef = ref();
	const loadingState = ref(false);//loading状态值
	const { proxy } = getCurrentInstance();
	let companyTitle = ref(proxy.$t("organization_departmentManagement.add_dep"));
	let drawerCompany = ref(false);
	let editShow = ref(true);
	//表单参数结构
	const companyForm = ref({});
	const companyRules = reactive({
		org_cn: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "blur" }],
		org_ru: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "blur" }],
		// personnel_size: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "blur" }],
		parent_id: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "change" }],
	});

	//保存并添加
	const saveContinue = (typebtn: string, formEl: FormInstance | undefined) => {
		submitForm(typebtn, formEl)
	}
	//保存

	const submitForm = async (typebtn: string, formEl: FormInstance | undefined) => {
		if (!formEl) return;
		await formEl.validate((valid, fields) => {
			if (valid) {
				//保存
				loadingState.value = true;
				saveOrgsApi(companyForm.value).then(res => {
					console.log(res);
					loadingState.value = false;
					if (res.code == ResultEnum.SUCCESS) {
						getAlltree();//初始化组织架构
						successMsg(proxy.$t("merak.action_success"));
						if (typebtn == 1) {
							//关闭弹窗
							drawerCompany.value = false;

						}
						formEl.resetFields();
						companyForm.value = resetForm();//清空表单
						tableRef.value?.reloadData();//刷新表格


						return;
					} else {
						failMsg(res.message)
					}
					// if (res.code == ResultEnum.ERROR) {

					// }
				})
			} else {
				console.log("error submit!", fields);
			}
		});
	};


	//删除
	const delCompany = (rows) => {
		delConfimMsg({
			callback: val => {
				if (val == "confirm") {
					delOrgsApi({ org_id: rows.org_id }).then(res => {
						if (res.code == ResultEnum.SUCCESS) {
							successMsg(proxy.$t("merak.delete_success"));
							tableRef.value?.reloadData();
						}
						if (res.code == ResultEnum.ERROR) {
							failMsg(res.message)
						}

					})
				}
			}
		});
	}

	//编辑
	const saveEdit = (rows) => {
		console.log(rows)
		let { org_id, parent_id, org_cn, org_ru, personnel_size } = JSON.parse(JSON.stringify(rows));
		companyRef.value?.resetFields();
		companyForm.value = {
			org_id: org_id,//组织id  新增时不需要
			parent_id: parent_id,//父级id  添加公司时为0
			org_type: 1,////组织类型 0-公司1-部门
			org_cn: org_cn,//组织名称(中文)
			org_ru: org_ru,//组织名称(俄文)
			personnel_size: personnel_size,//人员编制
		};
		//打开弹窗
		drawerCompany.value = true;
		editShow.value = false;
		companyTitle.value = proxy.$t("organization_departmentManagement.edit_dep");
	}
	//取消
	const cancelEmpty = (formEl: FormInstance | undefined) => {
		if (!formEl) return;
		formEl.resetFields();
		drawerCompany.value = false;
	}
	//新增
	const onPlus = () => {
		drawerCompany.value = true;
		editShow.value = true;
		companyTitle.value = proxy.$t("organization_departmentManagement.add_dep");
		companyForm.value = resetForm();
	}
	const resetForm = () => {
		companyRef.value?.resetFields();
		return {
			org_id: 0,//组织id  新增时不需要
			parent_id: Number(org_ids.value),//父级id  添加公司时为0
			org_type: 1,////组织类型 0-公司1-部门
			org_cn: "",//组织名称(中文)
			org_ru: "",//组织名称(俄文)
			personnel_size: "",//人员编制
		}
	}
	//#endregion



	//#region 列表



	// 页面配置数据
	let authArr = ref({});
	const state = reactive < {

		org_id: string,
		key_words: string,
		columnType: Object
	} > ({
		org_id: '',
		key_words: '',
		columnType: {}
	});

	// 动态计算表格的外部筛选数据
	const params = computed(() => ({ key_words: state.key_words, org_id: state.org_id ,org_type:1}));
	const columnTypeNew = computed(() => ([].concat(state.columnType)))

	// 表格配置属性
	const tablePayload = reactive < MerakXTableProps > ({
		// 列设置存储的数据对照值
		columnsByStore: [],
		// 表格行数据的唯一 key, 跟后端同步
		rowKey: "org_id",
		// 初始化的外部筛选数据
		params,

		//导出
		enabledExport: false,
		// 展示选中列及操作列, 可通过传入对象形式扩展特殊列的渲染插槽, 例如
		columnType: columnTypeNew,
		// columnType: ['selection', "multiple", "handle"],
		// 批量操作选项
		batches: [{ type: "delete", text: "批量删除", color: "red" }],
		// 操作列选项
		// handles: [{ type: "delete", text: "删除", color: "red" }]
	});

	//获取数据
	//查询

	const searchFn = (e) => {
		state.key_words = e.search;
	}
	// const getDepFun = (e) => {
	// 	console.log(e)
	// 	state.org_id = e;
	// }
	//列表内容展示区
	const handleQueryData: MerakXTableInstance["queryData"] = async ({ page, sorts, filters, from }) => {
		const params: Record<string, any> = { };
		if (!!page) {
			Object.assign(params, { ...page }, from);
		}
		return await getOrgsTableListApi(params, "departmentManagement").then(res => {
			//  ========权限判断 start  ======
			let authList = res?.auth_list;
			if (authList) {
				authArr.value = authList;
				if (authList?.depEdit.show || authList?.depDel.show) {
					state.columnType = { type: 'handle', width: proxy.$t("lang") == 'zh' ? 120 : 220, slot: 'handler' };
				}
				tablePayload.enabledExport = !!res?.auth_list?.export?.show;
			}
			// ========权限判断 end  ======
			// 数据接口 start  ======
			if (res.code == ResultEnum.SUCCESS) {
				let data = res.data;
				const { table_data, language } = data as { table_data: Record<string, any>; language: Record<string, any> };

				return table_data;
			}
		})

	};


	// 获取表头数据
	const handleQueryColumns: MerakXTableInstance["queryColumns"] = async () => {
		// 初始化接口需要传入队列 loading 暴露的 id
		return getDepHeadApi().then(({ code, data }) => {
			if (code == ResultEnum.SUCCESS) {
				// 克隆表头数据作为列设置的对照数据
				tablePayload.columnsByStore = JSON.parse(JSON.stringify(data.columns));
				return {
					...data,
					columns: [...data.columns].map(column => {
						switch (column.field) {
							// 匹配列字段用于扩展自定义
							case "department_cn":
							case "department_ru":
								// 固定列
								column.fixed = "left";
								return column;
							default:
								return column;
						}
					})
				};
			}
		});
	};
	//#endregion

	//#region  初始化接口

	//初始化获取所有公司
	let companyList = ref([]);
	const getOrgsList = (params) => {
		getOrgsListApi(params).then(res => {
			if (res.code == ResultEnum.SUCCESS) {
				companyList.value = res.data;
			}
		})
	}
	onMounted(() => {
		getOrgsList({ org_id: 0 });//初始化获取所有公司
	})
	//#endregion

</script>

<style scoped lang="scss">
	@import "./index.scss";
</style>